package com.apache.uct.common.filter;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.apache.passport.common.XmlWhiteUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.entity.Act;

public abstract class UctSupperFilter implements Filter {

	private Logger logger = Logger.getLogger(UctSupperFilter.class);

	protected Map<String, ArrayList<String>> whiteMap = new HashMap<String, ArrayList<String>>();
	protected String[] mobileAgents = { "iphone", "android", "phone", "mobile", "wap", "netfront", "java",
			"opera mobi", "opera mini", "ucweb", "windows ce", "symbian", "series", "webos", "sony", "blackberry",
			"dopod", "nokia", "samsung", "palmsource", "xda", "pieplus", "meizu", "midp", "cldc", "motorola", "foma",
			"docomo", "up.browser", "up.link", "blazer", "helio", "hosin", "huawei", "novarra", "coolpad", "webos",
			"techfaith", "palmsource", "alcatel", "amoi", "ktouch", "nexian", "ericsson", "philips", "sagem",
			"wellcom", "bunjalloo", "maui", "smartphone", "iemobile", "spice", "bird", "zte-", "longcos", "pantech",
			"gionee", "portalmmm", "jig browser", "hiptop", "benq", "haier", "^lct", "320x320", "240x320", "176x220",
			"w3c ", "acs-", "alav", "alca", "amoi", "audi", "avan", "benq", "bird", "blac", "blaz", "brew", "cell",
			"cldc", "cmd-", "dang", "doco", "eric", "hipt", "inno", "ipaq", "java", "jigs", "kddi", "keji", "leno",
			"lg-c", "lg-d", "lg-g", "lge-", "maui", "maxo", "midp", "mits", "mmef", "mobi", "mot-", "moto", "mwbp",
			"nec-", "newt", "noki", "oper", "palm", "pana", "pant", "phil", "play", "port", "prox", "qwap", "sage",
			"sams", "sany", "sch-", "sec-", "send", "seri", "sgh-", "shar", "sie-", "siem", "smal", "smar", "sony",
			"sph-", "symb", "t-mo", "teli", "tim-", "tosh", "tsm-", "upg1", "upsi", "vk-v", "voda", "wap-", "wapa",
			"wapi", "wapp", "wapr", "webc", "winw", "winw", "xda", "xda-", "Googlebot-Mobile" };

	protected boolean canAccessSupper(LoginUser loginUser, String path) {
		boolean mark = false;
		Map<String, Act> acts = loginUser.getActMap();
		logger.info(acts);
		if (null != acts && !acts.isEmpty()) {
			for (String key : acts.keySet()) {
				Act act = acts.get(key);
				if (StrUtil.isNotNull(act.getActUrl())) {
					String str[] = act.getActUrl().split(",");
					for (int i = 0; i < str.length; i++) {
						if (str[i].endsWith(".action")) {
							if (path.equals(str[i]))
								return true;
						} else if (path.startsWith(str[i])) {
							return true;
						}
					}
				}
			}
		}
		return mark;
	}

	protected boolean JudgeIsMoblie(HttpServletRequest request) {
		boolean isMoblie = false;
		String mobileType = request.getParameter("userAgent");
		if (StrUtil.isNotNull(mobileType)) {
			return true;
		}
		if (request.getHeader("User-Agent") != null) {
			for (String mobileAgent : mobileAgents) {
				if (request.getHeader("User-Agent").toLowerCase().indexOf(mobileAgent) >= 0) {
					isMoblie = true;
					break;
				}
			}
		}
		return isMoblie;
	}

	protected boolean unlockPath(String path) {
		XmlWhiteUtils.getInstance().deWhiteXml(whiteMap);
		ArrayList<String> whiteUrl = (ArrayList<String>) whiteMap.get("whiteUrl");
		ArrayList<String> whiteParadigm = (ArrayList<String>) whiteMap.get("whiteParadigm");
		int wp = whiteParadigm.size();
		if (path.length() > 1) {
			if (whiteUrl.contains(path)) {
				return true;
			}
			for (int i = 0; i < wp; i++) {
				if ((whiteParadigm.get(i)).contains("*")) {
					String wdir = (whiteParadigm.get(i)).replace("*", "");
					int s = path.indexOf(wdir);
					if (s == 0) {
						return true;
					}
				} else if (!"".equals(whiteParadigm.get(i))) {
					int s = path.indexOf(whiteParadigm.get(i));
					if (s == 0) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	* 清空系统信息
	*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected void clearLoginInfo(HttpServletRequest req, HttpServletResponse resp) {
		LoginUser loginUser = (LoginUser) req.getSession().getAttribute("loginUser");
		if (null == loginUser)
			return;
		Cookie[] cookies = req.getCookies();
		try {
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = new Cookie(cookies[i].getName(), null);
				cookie.setMaxAge(0);
				cookie.setPath("/");//根据你创建cookie的路径进行填写    
				resp.addCookie(cookie);
			}
		} catch (Exception ex) {
		}
		ArrayList lst = new ArrayList();
		Enumeration enumer = req.getSession().getAttributeNames();
		while (enumer.hasMoreElements()) {
			lst.add(enumer.nextElement());
		}
		for (int i = 0; i < lst.size(); i++) {
			req.getSession().removeAttribute(lst.get(i).toString());
		}
	}
}
